﻿#include "TrainAdminDialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include "Global_Class.h"
#include "trains.h"
#include <deque>


//TrainAdminDialog::TrainAdminDialog(QWidget* parent)
//    : QDialog(parent)
//{
//    setWindowTitle("列车信息管理");
//    QVBoxLayout* mainLayout = new QVBoxLayout(this);
//    table = new QTableWidget(this);
//    table->setColumnCount(4);
//    table->setHorizontalHeaderLabels({"列车ID", "车次号", "起始站ID", "终到站ID"});
//    table->setSelectionBehavior(QAbstractItemView::SelectRows);
//    mainLayout->addWidget(table);
//    QHBoxLayout* inputLayout = new QHBoxLayout();
//    idEdit = new QLineEdit(this);
//    idEdit->setPlaceholderText("列车ID");
//    codeEdit = new QLineEdit(this);
//    codeEdit->setPlaceholderText("车次号");
//    startStationEdit = new QLineEdit(this);
//    startStationEdit->setPlaceholderText("起始站ID");
//    endStationEdit = new QLineEdit(this);
//    endStationEdit->setPlaceholderText("终到站ID");
//    inputLayout->addWidget(idEdit);
//    inputLayout->addWidget(codeEdit);
//    inputLayout->addWidget(startStationEdit);
//    inputLayout->addWidget(endStationEdit);
//    addBtn = new QPushButton("添加", this);
//    editBtn = new QPushButton("修改", this);
//    deleteBtn = new QPushButton("删除", this);
//	undoBtn = new QPushButton("撤销", this);
//	redoBtn = new QPushButton("恢复", this);
//    inputLayout->addWidget(addBtn);
//    inputLayout->addWidget(editBtn);
//    inputLayout->addWidget(deleteBtn);
//	inputLayout->addWidget(undoBtn);
//	inputLayout->addWidget(redoBtn);
//    mainLayout->addLayout(inputLayout);
//    QHBoxLayout* searchLayout = new QHBoxLayout();
//    searchEdit = new QLineEdit(this);
//    searchEdit->setPlaceholderText("按车次号查询");
//    searchBtn = new QPushButton("查询", this);
//    searchLayout->addWidget(searchEdit);
//    searchLayout->addWidget(searchBtn);
//    mainLayout->addLayout(searchLayout);
//    infoLabel = new QLabel(this);
//    mainLayout->addWidget(infoLabel);
//    refreshTrainTable();
//    connect(addBtn, &QPushButton::clicked, this, &TrainAdminDialog::onAddTrain);
//    connect(deleteBtn, &QPushButton::clicked, this, &TrainAdminDialog::onDeleteTrain);
//    connect(editBtn, &QPushButton::clicked, this, &TrainAdminDialog::onEditTrain);
//    connect(searchBtn, &QPushButton::clicked, this, &TrainAdminDialog::onSearchTrain);
//	connect(undoBtn, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.undoAction()) {
//            refreshTrainTable();
//            showInfo("撤销成功");
//        } else {
//            showInfo("没有可撤销的操作");
//        }
//    });
//    connect(redoBtn, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.redoAction()) {
//            refreshTrainTable();
//            showInfo("恢复成功");
//        } else {
//            showInfo("没有可恢复的操作");
//        }
//		});
//
//}

//以下为UI美化后的代码----------------------------------------------------------------------
TrainAdminDialog::TrainAdminDialog(QWidget* parent)
    : QDialog(parent)
{
    setWindowTitle("列车信息管理");
    setMinimumSize(1000, 600);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // 设置字体
    QFont globalFont("Microsoft YaHei", 10);
    QFont headerFont("Microsoft YaHei", 10, QFont::Bold);
    setFont(globalFont);

    // 主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    // === 标题区域 ===
    QLabel* titleLabel = new QLabel("列车信息管理", this);
    titleLabel->setFont(QFont("Microsoft YaHei", 14, QFont::Bold));
    titleLabel->setStyleSheet("color: #2c3e50; padding: 8px 0;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // === 表格区域 ===
    QFrame* tableFrame = new QFrame(this);
    tableFrame->setFrameStyle(QFrame::StyledPanel);
    tableFrame->setStyleSheet("QFrame { background-color: white; border-radius: 8px; }");

    QVBoxLayout* tableLayout = new QVBoxLayout(tableFrame);
    tableLayout->setContentsMargins(12, 12, 12, 12);

    // 表格标题栏
    QHBoxLayout* tableHeaderLayout = new QHBoxLayout();
    QLabel* tableTitle = new QLabel("列车数据", this);
    tableTitle->setFont(headerFont);
    tableTitle->setStyleSheet("color: #34495e;");
    tableHeaderLayout->addWidget(tableTitle);
    tableHeaderLayout->addStretch();

    // 记录计数
    recordCountLabel = new QLabel("总计: 0 条记录", this);
    recordCountLabel->setStyleSheet("color: #7f8c8d; font-size: 9pt;");
    tableHeaderLayout->addWidget(recordCountLabel);
    tableLayout->addLayout(tableHeaderLayout);

    // 表格控件
    table = new QTableWidget(this);
    table->setColumnCount(4);
    table->setHorizontalHeaderLabels({ "列车ID", "车次号", "起始站ID", "终到站ID" });
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setSelectionMode(QAbstractItemView::SingleSelection);

    // 表格样式优化
    table->horizontalHeader()->setFont(headerFont);
    table->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    table->horizontalHeader()->setStretchLastSection(true);
    table->horizontalHeader()->setMinimumSectionSize(100);

    // 设置列宽
    table->setColumnWidth(0, 120); // 列车ID
    table->setColumnWidth(1, 150); // 车次号
    table->setColumnWidth(2, 120); // 起始站ID
    table->setColumnWidth(3, 120); // 终到站ID

    table->verticalHeader()->setVisible(false);
    table->setShowGrid(false);
    table->setAlternatingRowColors(true);
    table->setSortingEnabled(true);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    tableLayout->addWidget(table);
    mainLayout->addWidget(tableFrame, 1);

    // === 操作区域 ===
    QFrame* controlFrame = new QFrame(this);
    controlFrame->setFrameStyle(QFrame::StyledPanel);
    controlFrame->setStyleSheet("QFrame { background-color: #f8f9fa; border-radius: 8px; }");

    QVBoxLayout* controlLayout = new QVBoxLayout(controlFrame);
    controlLayout->setContentsMargins(15, 15, 15, 15);
    controlLayout->setSpacing(12);

    // 输入区域
    QHBoxLayout* inputLayout = new QHBoxLayout();
    inputLayout->setSpacing(12);

    // 创建输入框的lambda函数
    auto createLineEdit = [this, globalFont](const QString& placeholder, int minWidth = 120) {
        QLineEdit* edit = new QLineEdit(this);
        edit->setPlaceholderText(placeholder);
        edit->setMinimumWidth(minWidth);
        edit->setFont(globalFont);
        edit->setClearButtonEnabled(true);
        return edit;
        };

    // 初始化输入框
    idEdit = createLineEdit("列车ID", 100);
    codeEdit = createLineEdit("车次号 (如: G1234)", 120);
    startStationEdit = createLineEdit("起始站ID", 100);
    endStationEdit = createLineEdit("终到站ID", 100);

    // 添加输入框标签的lambda函数
    auto addInputWithLabel = [this, inputLayout](const QString& labelText, QLineEdit* edit) {
        QVBoxLayout* vLayout = new QVBoxLayout();
        vLayout->setSpacing(4);
        QLabel* label = new QLabel(labelText, this);
        label->setStyleSheet("color: #2c3e50; font-size: 9pt;");
        vLayout->addWidget(label);
        vLayout->addWidget(edit);
        inputLayout->addLayout(vLayout);
        };

    addInputWithLabel("列车ID", idEdit);
    addInputWithLabel("车次号", codeEdit);
    addInputWithLabel("起始站ID", startStationEdit);
    addInputWithLabel("终到站ID", endStationEdit);

    controlLayout->addLayout(inputLayout);

    // 按钮区域
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);

    // 创建按钮的lambda函数
    auto createButton = [this](const QString& text, const QString& color, const QString& hoverColor) {
        QPushButton* btn = new QPushButton(text, this);
        btn->setMinimumSize(80, 36);
        btn->setCursor(Qt::PointingHandCursor);

        QString style = QString(
            "QPushButton { "
            "    background-color: %1; "
            "    color: white; "
            "    border: none; "
            "    border-radius: 6px; "
            "    padding: 8px 16px; "
            "    font-weight: bold; "
            "} "
            "QPushButton:hover { "
            "    background-color: %2; "
            "} "
            "QPushButton:pressed { "
            "    background-color: %1; "
            "} "
            "QPushButton:disabled { "
            "    background-color: #bdc3c7; "
            "    color: #7f8c8d; "
            "}"
        ).arg(color, hoverColor);

        btn->setStyleSheet(style);
        return btn;
        };

    // 初始化功能按钮
    addBtn = createButton("添加列车", "#27ae60", "#219653");
    editBtn = createButton("修改列车", "#3498db", "#2980b9");
    deleteBtn = createButton("删除列车", "#e74c3c", "#c0392b");
    undoBtn = createButton("撤销", "#f39c12", "#e67e22");
    redoBtn = createButton("恢复", "#9b59b6", "#8e44ad");

    buttonLayout->addWidget(addBtn);
    buttonLayout->addWidget(editBtn);
    buttonLayout->addWidget(deleteBtn);
    buttonLayout->addStretch();
    buttonLayout->addWidget(undoBtn);
    buttonLayout->addWidget(redoBtn);

    controlLayout->addLayout(buttonLayout);

    // 搜索区域
    QHBoxLayout* searchLayout = new QHBoxLayout();
    searchLayout->setSpacing(10);

    QLabel* searchLabel = new QLabel("快速搜索:", this);
    searchLabel->setStyleSheet("color: #2c3e50; font-weight: bold;");

    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("输入车次号进行查询...");
    searchEdit->setMinimumWidth(250);
    searchEdit->setClearButtonEnabled(true);
    searchEdit->setStyleSheet(
        "QLineEdit { "
        "    padding: 8px 12px; "
        "    border: 2px solid #e0e0e0; "
        "    border-radius: 6px; "
        "    background-color: white; "
        "    color: #2c3e50;"
        "} "
        "QLineEdit:focus { "
        "    border-color: #3498db; "
        "}"
    );

    searchBtn = createButton("搜索", "#3498db", "#2980b9");
    QPushButton* resetBtn = createButton("重置", "#95a5a6", "#7f8c8d");

    searchLayout->addWidget(searchLabel);
    searchLayout->addWidget(searchEdit);
    searchLayout->addWidget(searchBtn);
    searchLayout->addWidget(resetBtn);
    searchLayout->addStretch();

    controlLayout->addLayout(searchLayout);
    mainLayout->addWidget(controlFrame);

    // === 状态信息区域 ===
    QHBoxLayout* statusLayout = new QHBoxLayout();

    infoLabel = new QLabel("就绪", this);
    infoLabel->setStyleSheet(
        "QLabel { "
        "    color: #7f8c8d; "
        "    padding: 8px 12px; "
        "    background-color: #ecf0f1; "
        "    border-radius: 4px; "
        "    font-size: 9pt; "
        "}"
    );
    infoLabel->setMinimumHeight(30);

    statusLayout->addWidget(infoLabel);
    mainLayout->addLayout(statusLayout);

    // 初始化数据
    refreshTrainTable();

    // 信号连接
    connect(addBtn, &QPushButton::clicked, this, &TrainAdminDialog::onAddTrain);
    connect(deleteBtn, &QPushButton::clicked, this, &TrainAdminDialog::onDeleteTrain);
    connect(editBtn, &QPushButton::clicked, this, &TrainAdminDialog::onEditTrain);
    connect(searchBtn, &QPushButton::clicked, this, &TrainAdminDialog::onSearchTrain);

    connect(resetBtn, &QPushButton::clicked, this, [this]() {
        searchEdit->clear();
        refreshTrainTable();
        showInfo("已重置搜索条件");
        });

    connect(undoBtn, &QPushButton::clicked, this, [this]() {
        if (undoRedo.undoAction()) {
            refreshTrainTable();
            showInfo("撤销成功");
        }
        else {
            showInfo("没有可撤销的操作");
        }
        });

    connect(redoBtn, &QPushButton::clicked, this, [this]() {
        if (undoRedo.redoAction()) {
            refreshTrainTable();
            showInfo("恢复成功");
        }
        else {
            showInfo("没有可恢复的操作");
        }
        });

    // 表格选择变化时更新输入框
    connect(table, &QTableWidget::itemSelectionChanged, this, [this]() {
        auto selectedItems = table->selectedItems();
        if (!selectedItems.isEmpty()) {
            int row = table->currentRow();
            idEdit->setText(table->item(row, 0)->text());
            codeEdit->setText(table->item(row, 1)->text());
            startStationEdit->setText(table->item(row, 2)->text());
            endStationEdit->setText(table->item(row, 3)->text());
        }
        });

    // 设置全局样式表
    setStyleSheet(R"(
        /* 主窗口样式 */
        QDialog {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #f5f7fa, stop: 1 #e4e7ec);
            color: #333333;
        }

        /* 表格样式优化 */
        QTableWidget {
            background-color: white;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            gridline-color: #f0f0f0;
            outline: none;
        }
        QTableWidget::item {
            border: none;
            padding: 8px 12px;
            color: #2c3e50;
            border-bottom: 1px solid #f8f9fa;
        }
        QTableWidget::item:selected {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        QTableWidget::item:hover {
            background-color: #f5f5f5;
        }
        QTableWidget::item:alternate {
            background-color: #fafbfc;
        }
        QHeaderView::section {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #34495e, stop: 1 #2c3e50);
            color: white;
            padding: 12px 15px;
            border: none;
            font-weight: bold;
            border-right: 1px solid #455a64;
        }
        QHeaderView::section:last {
            border-right: none;
        }

        /* 输入框统一样式 */
        QLineEdit {
            background-color: white;
            color: #2c3e50;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 9pt;
        }
        QLineEdit:focus {
            border-color: #3498db;
            background-color: #fafcff;
        }
        QLineEdit::placeholder {
            color: #a0a0a0;
        }

        /* 滚动条样式 */
        QScrollBar:vertical {
            background: #f0f0f0;
            width: 12px;
            margin: 0px;
        }
        QScrollBar::handle:vertical {
            background: #c0c0c0;
            border-radius: 6px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: #a0a0a0;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            height: 0px;
        }
    )");
}

// 在类中添加更新记录计数的方法
void TrainAdminDialog::updateRecordCount()
{
    int count = table->rowCount();
    recordCountLabel->setText(QString("总计: %1 条记录").arg(count));
}



//这之下是源代码----------------------------------------------------

void TrainAdminDialog::refreshTrainTable() {
    table->setRowCount(0);
    for (const auto& tr : allData->trainQueue) {
        int row = table->rowCount();
        table->insertRow(row);
        table->setItem(row, 0, new QTableWidgetItem(QString::number(tr.getTrainId())));
        table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(tr.getTrainCode())));
        table->setItem(row, 2, new QTableWidgetItem(QString::number(tr.getStartStationId())));
        table->setItem(row, 3, new QTableWidgetItem(QString::number(tr.getEndStationId())));
    }
    updateRecordCount();
}

void TrainAdminDialog::showInfo(const QString& msg) {
    infoLabel->setText(msg);
}

void TrainAdminDialog::onAddTrain() {
    bool okId, okStart, okEnd;
    int id = idEdit->text().toInt(&okId);
    QString code = codeEdit->text().trimmed();
    int startId = startStationEdit->text().toInt(&okStart);
    int endId = endStationEdit->text().toInt(&okEnd);
    if (!okId || code.isEmpty() || !okStart || !okEnd) {
        showInfo("请输入合法的列车ID、车次号、起始站ID和终到站ID");
        return;
    }
    for (const auto& tr : allData->trainQueue) {
        if (tr.getTrainId() == id || QString::fromStdString(tr.getTrainCode()) == code) {
            showInfo("列车ID或车次号已存在");
            return;
        }
    }
    // 检查站点ID是否存在
    bool startExist = false, endExist = false;
    for (const auto& st : allData->stationsQueue) {
        if (st.getStationId() == startId) startExist = true;
        if (st.getStationId() == endId) endExist = true;
    }
    if (!startExist || !endExist) {
        showInfo("起始站或终到站ID不存在");
        return;
    }
    // 构造trains对象时补充type参数，假设为'G'（高铁），如有其它类型可扩展
    std::string codeStr = code.toStdString();
    trains newTrain(id, codeStr, 'G', startId, endId);
    allData->trainQueue.push_back(newTrain);
	undoRedo.recordOp(Operation_tr::makeSingle(Add, newTrain, allData->trainQueue.size() - 1));
    //allData->Train_WriteToFile("train.txt");
    refreshTrainTable();
    showInfo("添加成功");
}

void TrainAdminDialog::onDeleteTrain() {
    QList<QTableWidgetItem*> selected = table->selectedItems();
    if (selected.isEmpty()) {
        showInfo("请选择要删除的列车");
        return;
    }
    int row = table->row(selected.first());
    int id = table->item(row, 0)->text().toInt();
    auto& queue = allData->trainQueue;
    auto it = std::find_if(queue.begin(), queue.end(), [id](const trains& tr) { return tr.getTrainId() == id; });
    if (it == queue.end()) {
        showInfo("列车不存在");
        return;
    }

	std::deque<train_schedule>::iterator startPos;
	std::deque<train_schedule>::iterator endPos;
    for (startPos = allData->trainSchedules.begin(); startPos != allData->trainSchedules.end(); startPos++) {
        if (startPos->getTrainId() == it->getTrainId()) {
			break;
        }
    }
    for (endPos = startPos; endPos != allData->trainSchedules.end(); endPos++) {
        if (endPos->getTrainId() != it->getTrainId()) {
			break;
        }
    }

    if (startPos != allData->trainSchedules.end()) {
        allData->trainSchedules.erase(startPos, endPos);
	}

	undoRedo.recordOp(Operation_tr::makeSingle(Delete, *it, row)); // 记录删除操作
    
    queue.erase(it);
    //allData->Train_WriteToFile("train.txt");
    refreshTrainTable();
    showInfo("删除成功");
}

void TrainAdminDialog::onEditTrain() {
    QList<QTableWidgetItem*> selected = table->selectedItems();
    if (selected.isEmpty()) {
        showInfo("请选择要修改的列车");
        return;
    }
    int row = table->row(selected.first());
    int id = table->item(row, 0)->text().toInt();
    QString newCode = codeEdit->text().trimmed();
    int newStartId = startStationEdit->text().toInt();
    int newEndId = endStationEdit->text().toInt();
    if (newCode.isEmpty() || newStartId == 0 || newEndId == 0) {
        showInfo("请输入新的车次号、起始站ID和终到站ID");
        return;
    }
    auto& queue = allData->trainQueue;
    auto it = std::find_if(queue.begin(), queue.end(), [id](const trains& tr) { return tr.getTrainId() == id; });
    if (it == queue.end()) {
        showInfo("列车不存在");
        return;
    }
    // 检查站点ID是否存在
    bool startExist = false, endExist = false;
    for (const auto& st : allData->stationsQueue) {
        if (st.getStationId() == newStartId) startExist = true;
        if (st.getStationId() == newEndId) endExist = true;
    }
    if (!startExist || !endExist) {
        showInfo("起始站或终到站ID不存在");
        return;
    }
    std::string codeStr = newCode.toStdString();

    trains old = *it;          // 复制旧对象

    it->setTrainCode(codeStr);
    it->setStartStationId(newStartId);
    it->setEndStationId(newEndId);

    trains edited = *it;
    // —— 记录 —— 
    Operation_tr op;
    op.type = Modify;
    op.Trains = { old, edited };  // 0 = 旧, 1 = 新
    op.indices = { row };
    undoRedo.recordOp(op);

    //allData->Train_WriteToFile("train.txt");
    refreshTrainTable();
    showInfo("修改成功");
}

void TrainAdminDialog::onSearchTrain() {
    QString keyword = searchEdit->text().trimmed();
    table->setRowCount(0);
    for (const auto& tr : allData->trainQueue) {
        if (QString::fromStdString(tr.getTrainCode()).contains(keyword)) {
            int row = table->rowCount();
            table->insertRow(row);
            table->setItem(row, 0, new QTableWidgetItem(QString::number(tr.getTrainId())));
            table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(tr.getTrainCode())));
            table->setItem(row, 2, new QTableWidgetItem(QString::number(tr.getStartStationId())));
            table->setItem(row, 3, new QTableWidgetItem(QString::number(tr.getEndStationId())));
        }
    }
    showInfo("查询完成");
}
